<?php


namespace app\api\library\index\collageGoods;


use app\api\model\MallCollage;
use app\api\model\MallGoods;
use app\api\model\MallOrder;
use app\api\model\MallUser;
use think\facade\Db;

class V
{
    public static function run($param)
    {
        $limit  = $param[ 'limit' ];
        $page   = $param[ 'page' ];
        $userId = _checkEmptyParam($param[ 'userId' ], '用户ID不能为空');
        $offset = ($page - 1) * $limit;
        
        $collage     = Db::table('ea_mall_collage')
//            ->limit($offset, $limit)
            ->field('collage_id,collage_no,goods_id,start_time,end_time,failure_reward,success_reward,collage_num+1 as collage_num,join_num+1 as join_num')
            ->where([['status', '=', 1], ['end_time', '>', time()], ['finish_time', '=', null], ['fail_time', '=', 0]])
            ->order(['collage_id' => 'desc'])
            ->select()->toArray();
        $collageIds  = array_column($collage, 'collage_id');
        $collageIds1 = Db::table('ea_mall_order')
            ->where([['order_status', '=', 10], ['collage_id', 'in', $collageIds], ['user_id', '=', $userId]])
            ->order(['collage_id' => 'desc'])
            ->column('collage_id');
        $collageIds  = implode(',', $collageIds1) . ',' . implode(',', $collageIds);
//        halt($collageIds);
        $where = self::getWhere($param);
        if (empty($where)) {
            $page = [
                'total'      => 0,
                'limit'      => $limit,
                'page'       => $page,
                'total_page' => ceil(0 / $limit),
            ];
            $res  = [
                'page' => $page,
                'list' => [],
            ];
            _outPut(200, $res);
        }
        if ( !empty($collageIds1)) {
            $collage = Db::table('ea_mall_collage')
                ->limit($offset, $limit)
                ->field('collage_id,user_id,collage_no,goods_id,start_time,end_time,failure_reward,success_reward,collage_num+1 as collage_num,join_num+1 as join_num')
                ->where($where)
                ->orderRaw("Field(collage_id,$collageIds)")
//                ->order(['collage_id' => 'desc'])
                ->select()->toArray();
        } else {
            $collage = Db::table('ea_mall_collage')
                ->limit($offset, $limit)
                ->field('collage_id,user_id,collage_no,goods_id,start_time,end_time,failure_reward,success_reward,collage_num+1 as collage_num,join_num+1 as join_num')
                ->where($where)
                ->order(['collage_id' => 'desc'])
                ->select()->toArray();
        }
        $total = Db::table('ea_mall_collage')
            ->where($where)
            ->count();
        //查询当前用户参与的拼团
        $goodsIds   = array_column($collage, 'goods_id');
        $goods      = MallGoods::with([
            'spec' => function ($query) {
                $query->where('delete_time', '=', null);
            },
        ])
            ->where([['id', 'in', $goodsIds]])
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->removeOption('soft_delete')
            ->field('id,title,logo,market_price,discount_price,failure_reward,success_reward,virtual_sales,collage_num+1 as collage_num,is_novices_exclusive')
            ->select()->toArray();
        $userIds    = array_column($collage, 'user_id');
        $users      = MallUser::where([['id', 'in', $userIds]])->select()->toArray();
        $users      = array_column($users, null, 'id');
        $collageIds = array_column($collage, 'collage_id');
        $orders     = Db::name('mall_order')->where([['collage_id', 'in', $collageIds], ['order_status', '>', 0], ['user_id', '=', $userId]])->select()->toArray();
        $orders     = array_column($orders, null, 'collage_id');
        foreach ($goods as $key => $value) {
            $goods[ $key ][ 'failure_reward' ] = getPrice($value[ 'failure_reward' ]);
            $goods[ $key ][ 'success_reward' ] = getPrice($value[ 'success_reward' ]);
            $goods[ $key ][ 'market_price' ]   = getPrice($value[ 'market_price' ]);
            $goods[ $key ][ 'discount_price' ] = getPrice($value[ 'discount_price' ]);
        }
        $goods = array_column($goods, null, 'id');
        foreach ($collage as $key => $value) {
            $collage[ $key ][ 'start_time' ] = date("Y-m-d H:i:s", $value[ 'start_time' ]);
            $collage[ $key ][ 'end_time' ]   = date("Y-m-d H:i:s", $value[ 'end_time' ]);
            $collage[ $key ][ 'goods' ]      = $goods[ $value[ 'goods_id' ] ] ?? '';
            //单独处理奖励金额
            if ( !empty($collage[ $key ][ 'goods' ])) {
                $collage[ $key ][ 'failure_reward' ] = $goods[ $value[ 'goods_id' ] ][ 'failure_reward' ];
                $collage[ $key ][ 'success_reward' ] = $goods[ $value[ 'goods_id' ] ][ 'success_reward' ];
            }
            $collage[ $key ][ 'user' ]     = $users[ $value[ 'user_id' ] ] ?? '';
            $collage[ $key ][ 'order_id' ] = $orders[ $value[ 'collage_id' ] ][ 'id' ] ?? 0;
            $collage[ $key ][ 'is_join' ]  = 0;
            if (in_array($value[ 'collage_id' ], $collageIds1)) {
                $collage[ $key ][ 'is_join' ] = 1;
            }
        }
        $isNovice = MallUser::where('id', $userId)->value('is_novice');
        $page     = [
            'total'      => $total,
            'limit'      => $limit,
            'page'       => $page,
            'total_page' => ceil($total / $limit),
        ];
        $res      = [
            'is_novice' => $isNovice,
            'page'      => $page,
            'list'      => $collage,
        ];
        _outPut(200, $res);
    }
    
    public static function getWhere($param)
    {
        $where = [
            ['status', '=', 1],
            ['finish_time', '=', null],
            ['fail_time', '=', 0],
            ['end_time', '>', time()],
        ];
        if ( !empty($param[ 'keywords' ])) {
            $collageIds = MallCollage::where([['collage_no', 'like', "%" . $param[ 'keywords' ] . "%"]])->column('collage_id');
            if ( !empty($collageIds)) {
                $where[] = ['collage_id', 'in', $collageIds];
            }
            $userIds = MallUser::where([['name', 'like', "%" . $param[ 'keywords' ] . "%"]])->column('id');
            if ( !empty($userIds)) {
                $where[] = ['user_id', 'in', $userIds];
            }
            if (empty($collageIds) && empty($userIds)) {
                return [];
            }
        }
        return $where;
    }
}